package main

import (
	"github.com/gorilla/websocket"
	"log"
	"net/http"
)

// 底层TCP缓冲区设置
var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin: func(r *http.Request) bool {
		//origin := r.Header.Get("Origin")
		//allowedOrigins := []string{"http://localhost:8080"}
		//for _, allowedOrigin := range allowedOrigins {
		//	if origin == allowedOrigin {
		//		return true
		//	}
		//}
		//return false
		return true
	},
}

func serverWs(hub *Hub, w http.ResponseWriter, r *http.Request) {
	// 1.鉴权
	token := r.URL.Query().Get("token")
	userId, err := validateToken(token)
	if err != nil {
		http.Error(w, "Unauthorized", http.StatusUnauthorized)
		return
	}
	// 2.协议升级
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Println("协议升级失败：" + err.Error())
		return
	}
	// 3.客户端初始化
	client := &Client{
		hub:   hub,
		conn:  conn,
		send:  make(chan []byte, 256),
		user:  userId,
		rooms: make(map[string]bool),
	}
	// 4.注册管理
	client.hub.register <- client // 注册客户端到hub

	// 5.启动reader与writer协程
	go client.writer()
	go client.reader()
}

// 解析验证token，返回用户id
func validateToken(token string) (string, error) {
	return token, nil
}
